#!/usr/bin/env python
# -*- coding: utf-8 -*-
from teamupshoppers import app

from flask import g, session
from flask.ext.login import current_user
import logging
from sqlite3 import dbapi2 as sqlite3


# configuration
DATABASE = 'teampupshoppers.db'

def connect_db():
    """Returns a new connection to the database."""
    return sqlite3.connect(DATABASE)

class DB(object):
    def query(self, query, args=(), one=False):
        """Queries the database and returns a list of dictionaries."""
        cur = self._execute(query, args)
        rv = [dict((cur.description[idx][0], value)
                   for idx, value in enumerate(row)) for row in cur.fetchall()]
        return (rv[0] if rv else None) if one else rv
        
    def execute(self, query, args=()):
        self._execute(query, args)
        g.db.commit()
        
    def _execute(self, query, args=()):
        return g.db.execute(query, args)
        
    def insert(self, query, args=()):
        cur = g.db.cursor()
        cur.execute(query, args)
        id = cur.lastrowid
        g.db.commit()
        return id

@app.before_request
def before_request():
    """Make sure we are connected to the database each request and look
    up the current user so that we know he's there.
    """
    g.db = connect_db()
    g.user = None
    if "user_id" in session:
        _db = DB()
        g.user = _db.query('select * from user where id = ?',
                          [session["user_id"]], one=True)


@app.teardown_request
def teardown_request(exception):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'db'):
        g.db.close()
